package com.by_man.presenter.module_health_records.access_records;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.by_man.presenter.R;
import com.by_man.presenter.SharedApplication;
import com.by_man.presenter.custom_layout.ImageLoaderAAA;
import com.by_man.presenter.main_page.MainActivity;
import com.by_man.presenter.module_gestureLock.GestureLockActivity;
import com.by_man.repository.IpAddress;
import com.by_man.repository.PostJsonArrayRequest;
import com.by_man.repository.PostStringRequest;
import com.by_man.repository.UserInfos;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;


/**
 * Created by man on 2017-03-16.
 */
public class AccessRecordsActivity extends AppCompatActivity {
    private ProgressDialog progressDialog;
    private RequestQueue rQueue;
    private int isInitImag = 0;
    private int isInitPhysical = 0;
    private int isInitExamine = 0;
    private int isInitHospital = 0;
    private int isInitMedinice = 0;
    private int isInitOCR = 0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_access_records);
        //rQueue = Volley.newRequestQueue(this);
        rQueue = SharedApplication.getrQueue(getApplication());
        rQueue.start();
        initView();
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra("position", 2);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            Intent intent = new Intent(this, MainActivity.class);
            intent.putExtra("position", 2);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
        return super.onKeyDown(keyCode,event);
    }

    protected void onRestart()
    {
        super.onRestart();
        Intent intent=new Intent(this,GestureLockActivity.class);
        intent.putExtra("class",this.getClass().getName());
        intent.putExtra("position", 2);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(intent);
    }

    private void initView() {
        // 初始化ToolBar
        Toolbar toolbar = (Toolbar)findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        ActionBar actionBar = getSupportActionBar();
        actionBar.setHomeAsUpIndicator(R.drawable.icon_back);
        actionBar.setDisplayHomeAsUpEnabled(true);

        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("提示信息");
        progressDialog.setMessage("请求数据，请稍后......");
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);

        final Button button_upload_file = (Button) findViewById(R.id.upload_file);
        final Button button_examination_report=(Button)findViewById(R.id.examination_report);
        final Button button_condition_report=(Button)findViewById(R.id.button_conditon_report);
        final Button button_hospital_history=(Button)findViewById(R.id.button_medical_history);
        final Button button_assy=(Button)findViewById(R.id.assay);

        //跳转到化验单
        button_assy.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(AccessRecordsActivity.this,OCRActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        //新档案上传界面
        button_upload_file.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //Intent intent = new Intent(AccessRecordsActivity.this, ImageLoaderAAA.class);
                //startActivity(intent);
            }
        });


        final Button button_yongyao= (Button) findViewById(R.id.yongyao);
        button_yongyao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccessRecordsActivity.this, MedicationRecordActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        //跳转到检查报告
        button_examination_report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccessRecordsActivity.this, ExamineRecordActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        //跳转到体检报告
        button_condition_report.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccessRecordsActivity.this, PhysicalExaminationActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        button_hospital_history.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AccessRecordsActivity.this, HospitalRecordActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });

        // 判断数据是否存在
        if (Images.imageThumbResetUrls == null || Images.imageThumbResetUrlsdata == null
                || UserInfos.Physical_Examination_Report == null
                || UserInfos.Examine_Report == null
                || UserInfos.Hospital_Records == null
                || UserInfos.Medinice_Report == null
                || UserInfos.OCR_Report == null) {
            progressDialog.show();
            HashMap<String, String> map = new HashMap<>();
            map.put("token", UserInfos.token);
            JSONObject jsonObject = new JSONObject(map);
            PostJsonArrayRequest jsonArrayRequest = new PostJsonArrayRequest(Request.Method.POST, IpAddress.Access_Health_Records, jsonObject,
                    new Response.Listener<JSONArray>() {
                        @Override
                        public void onResponse(JSONArray jsonArray) {
                            Images.imageThumbUrls.clear();
                            Images.imageThumbUrlsdata.clear();
                            try {
                                JSONObject temp;
                                for (int j = 0; j < jsonArray.length(); j++) {
                                    temp = (JSONObject) jsonArray.get(j);
                                    final String imgURL = IpAddress.Load_Image + temp.getString("path");
                                    final String update = temp.getString("updated_at");
                                    Images.imageThumbUrls.add(imgURL);
                                    Log.e("imageThumbUrls", imgURL);
                                    Images.imageThumbUrlsdata.add(update);
                                    Log.e("imageThumbUrlsdata", update);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            isInitImag = 1;
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            isInitImag = -1;
                            Log.e("AccessRecordsError", volleyError.getMessage(), volleyError);
                            Toast.makeText(AccessRecordsActivity.this, "连接失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
            rQueue.add(jsonArrayRequest);

            HashMap<String, String> paramsReport = new HashMap<>();
            paramsReport.put("token", UserInfos.token);
            paramsReport.put("json", "23");
            PostStringRequest stringRequest = new PostStringRequest(Request.Method.POST,
                    IpAddress.Report, paramsReport,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            UserInfos.Physical_Examination_Report = s;
                            isInitPhysical = 1;
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            isInitPhysical = -1;
                            Log.e("AccessRecordsError", volleyError.getMessage(), volleyError);
                            Toast.makeText(AccessRecordsActivity.this, "连接失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
            rQueue.add(stringRequest);

            HashMap<String, String> paramsReportExamine = new HashMap<>();
            paramsReportExamine.put("token", UserInfos.token);
            paramsReportExamine.put("json", "22");
            PostStringRequest stringRequestExamine = new PostStringRequest(Request.Method.POST,
                    IpAddress.Report, paramsReportExamine,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            UserInfos.Examine_Report = s;
                            isInitExamine = 1;
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            isInitExamine = -1;
                            Log.e("AccessRecordsError", volleyError.getMessage(), volleyError);
                            Toast.makeText(AccessRecordsActivity.this, "连接失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
            rQueue.add(stringRequestExamine);


            HashMap<String, String> paramsReportHospital = new HashMap<>();
            paramsReportHospital.put("token", UserInfos.token);
            paramsReportHospital.put("json", "24");
            PostStringRequest stringRequestHospital = new PostStringRequest(Request.Method.POST,
                    IpAddress.Report, paramsReportHospital,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            UserInfos.Hospital_Records = s;
                            isInitHospital = 1;
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            isInitHospital = -1;
                            Log.e("AccessRecordsError", volleyError.getMessage(), volleyError);
                            Toast.makeText(AccessRecordsActivity.this, "连接失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
            rQueue.add(stringRequestHospital);

            HashMap<String, String> paramsReportMedinice = new HashMap<>();
            paramsReportMedinice.put("token", UserInfos.token);
            PostStringRequest stringRequestMedinice = new PostStringRequest(Request.Method.POST,
                    IpAddress.Now_Medication, paramsReportMedinice,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            UserInfos.Medinice_Report = s;
                            isInitMedinice = 1;
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            isInitHospital = -1;
                            Log.e("AccessRecordsError", volleyError.getMessage(), volleyError);
                            Toast.makeText(AccessRecordsActivity.this, "连接失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
            rQueue.add(stringRequestMedinice);

            HashMap<String, String> paramsReportOCR = new HashMap<>();
            paramsReportOCR.put("token", UserInfos.token);
            PostStringRequest stringRequestOCR = new PostStringRequest(Request.Method.POST,
                    IpAddress.OCR, paramsReportOCR,
                    new Response.Listener<String>() {
                        @Override
                        public void onResponse(String s) {
                            UserInfos.OCR_Report = s;
                            isInitOCR = 1;
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError volleyError) {
                            isInitOCR = -1;
                            Log.e("AccessRecordsError", volleyError.getMessage(), volleyError);
                            Toast.makeText(AccessRecordsActivity.this, "连接失败！", Toast.LENGTH_SHORT).show();
                        }
                    });
            rQueue.add(stringRequestOCR);

            // 开启线程检查
            Thread monitor = new Thread() {
                public void run() {
                    long time = System.currentTimeMillis();
                    time += 1000 * 60 * 2;          // 两分钟
                    while (System.currentTimeMillis() < time) {
                        if (isInitImag == 1 && isInitPhysical == 1 && isInitExamine == 1
                                && isInitHospital == 1 && isInitMedinice == 1 && isInitOCR == 1) {
                            progressDialog.dismiss();
                            break;
                        }
                    }
                    progressDialog.dismiss();
                    if (System.currentTimeMillis() > time) {
                        button_upload_file.setClickable(false);
                        button_assy.setClickable(false);
                        button_condition_report.setClickable(false);
                        button_examination_report.setClickable(false);
                        button_hospital_history.setClickable(false);
                        button_yongyao.setClickable(false);
                    }
                }
            };
            monitor.setDaemon(true);
            monitor.start();
        }
    }
}
